<script setup lang="ts">
import { messageDB } from "@/utils/database";
import { dataFormat } from "@/utils/dataFormatting";
import { ElMessage } from "element-plus";
import { onMounted, onUnmounted, ref } from "vue";
// 使用public文件夹中的图片，确保在Electron环境中正确访问
import nullRequestImg from "@/assets/null_request.png";
const friendRequests = ref<any[]>([]);
const userSelf = ref<any>({});
// 加载状态
const acceptLoading = ref<boolean>(false);
const rejectLoading = ref<boolean>(false);

// 处理WebSocket消息
const handleWebSocketMessage = async (message: any) => {
  console.log("FriendRequestView -> 收到WebSocket消息:", dataFormat(message));
  if (message.type === "FRIEND_ACCEPT") {
    // 更新本地数据库状态
    try {
      const data = JSON.parse(message.content);
      await messageDB?.updateFriendRequestStatus(data.data.id, "accepted");
      // 刷新好友申请列表
      friendRequests.value = await messageDB?.getFriendRequestsByToUserId(
        userSelf.value?.id
      );
      // 刷新好友列表
      if (window.electronAPI.friendRequestUpdated) {
        window.electronAPI.friendRequestUpdated();
      }
    } catch (err) {
      console.error("更新好友申请状态失败:", err);
    }
  } else if (message.type === "FRIEND_REJECTED") {
    // 更新本地数据库状态
    try {
      const data = JSON.parse(message.content);
      await messageDB?.updateFriendRequestStatus(data.data.id, "rejected");
      // 刷新好友申请列表
      friendRequests.value = await messageDB?.getFriendRequestsByToUserId(
        userSelf.value?.id
      );
      // 刷新好友列表
      if (window.electronAPI.friendRequestUpdated) {
        window.electronAPI.friendRequestUpdated();
      }
    } catch (err) {
      console.error("更新好友申请状态失败:", err);
    }
  } else if (message.type === "FRIEND_EXISTS") {
    ElMessage.warning(message.content);
  }
};

// 同意好友申请
const handleAccept = async (item: any) => {
  try {
    // 加载状态设置为true
    acceptLoading.value = true;
    // 通过主进程发送同意好友申请的消息
    if (window.electronAPI && window.electronAPI.wsSend) {
      const messageData = {
        type: "acceptRequest",
        id: item.id,
        fromUserId: item.fromUserId,
        fromUserNickname: item.fromUserNickname,
        fromUserAvatar: item.fromUserAvatar,
        toUserId: item.toUserId,
        toUserNickname: item.toUserNickname,
        toUserAvatar: item.toUserAvatar,
        status: "accepted",
      };
      await window.electronAPI.wsSend(messageData);
    }
  } catch (error) {
    console.error("同意好友申请失败:", error);
    ElMessage.error("同意好友申请失败");
  } finally {
    // 加载状态设置为false
    acceptLoading.value = false;
  }
};

// 拒绝好友申请
const handleReject = async (item: any) => {
  try {
    // 加载状态设置为true
    rejectLoading.value = true;
    // 通过主进程发送拒绝好友申请的消息
    if (window.electronAPI && window.electronAPI.wsSend) {
      const messageData = {
        type: "rejectRequest",
        id: item.id,
        fromUserId: item.fromUserId,
        fromUserNickname: item.fromUserNickname,
        fromUserAvatar: item.fromUserAvatar,
        toUserId: item.toUserId,
        toUserNickname: item.toUserNickname,
        toUserAvatar: item.toUserAvatar,
        status: "rejected",
      };
      await window.electronAPI.wsSend(messageData);
    }
  } catch (error) {
    console.error("拒绝好友申请失败:", error);
    ElMessage.error("拒绝好友申请失败");
  } finally {
    // 加载状态设置为false
    rejectLoading.value = false;
  }
};

onMounted(async () => {
  // 从数据库中获取好友申请列表
  try {
    let electronAPI: any = (window as any).electronAPI;
    const user = await electronAPI.store.get("user");
    userSelf.value = user;
    const res = await messageDB?.getFriendRequestsByToUserId(user.id);
    friendRequests.value = res || [];
    // 注册WebSocket消息监听器
    if (electronAPI && electronAPI.onWsMessage) {
      electronAPI.onWsMessage(handleWebSocketMessage);
      console.log("FriendRequestView已注册WebSocket消息监听器");
    }
  } catch (err) {
    console.log("获取好友申请列表失败", err);
    ElMessage.error("获取好友申请列表失败");
  }
});

// 组件卸载时移除监听器
onUnmounted(() => {
  try {
    const electronAPI: any = (window as any).electronAPI;
    if (electronAPI && electronAPI.offWsMessage) {
      electronAPI.offWsMessage(handleWebSocketMessage);
      console.log("FriendRequestView已移除WebSocket消息监听器");
    }
  } catch (err) {
    console.log("移除WebSocket消息监听器失败", err);
  }
});
</script>

<template>
  <div class="friend-request-view">
    <el-card
      v-for="item in friendRequests"
      :key="item.id"
      shadow="hover"
      class="friend-request-card"
      v-if="friendRequests.length > 0"
    >
      <div class="content">
        <el-avatar shape="square" :size="36" :src="item.fromUserAvatar" />
        <div class="info">
          <span>{{ item.fromUserNickname }} 申请添加好友</span>
          <el-tooltip effect="dark" :content="item.note" placement="top">
            <span> 申请消息：{{ item.note }} </span>
          </el-tooltip>
        </div>
      </div>
      <div class="btn" v-if="item.status === 'pending'">
        <el-button
          type="primary"
          @click="handleAccept(item)"
          size="small"
          :loading="acceptLoading"
          >同意</el-button
        >
        <el-button type="danger" @click="handleReject(item)" size="small"
          >拒绝</el-button
        >
      </div>
      <div class="btn" v-else>
        <el-button
          type="success"
          size="small"
          disabled="true"
          v-if="item.status === 'accepted'"
          :loading="rejectLoading"
          >已添加</el-button
        >
        <el-button
          type="danger"
          size="small"
          disabled="true"
          v-if="item.status === 'rejected'"
          >已拒绝</el-button
        >
      </div>
    </el-card>
    <el-empty v-else :image="nullRequestImg" description="暂无好友申请" />
  </div>
</template>

<style lang="less" scoped>
.friend-request-view {
  width: 100%;
  height: 100%;
  padding: 10px;
  overflow-y: auto;
  background-color: #f2f3f9;
  .friend-request-card {
    height: 60px;
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    &:deep(.el-card__body) {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 100%;
      height: 100%;
      padding: 10px 12px;
      .content {
        display: flex;
        align-items: center;
        .info {
          margin-left: 10px;
          font-size: 13px;
          text-align: left;
          span {
            display: block;
            &:nth-child(2) {
              font-size: 11px;
            }
          }
        }
      }
    }
  }
}
</style>